/**
 * jQuery Yii ListView plugin file.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
 * @copyright Copyright &copy; 2008-2010 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @version $Id: jquery.yiilistview.js 3296 2011-06-22 17:15:17Z qiang.xue $
 */

;(function($) {
	/**
	 * yiiListView set function.
	 * @param options map settings for the list view. Availablel options are as follows:
	 * - ajaxUpdate: array, IDs of the containers whose content may be updated by ajax response
	 * - ajaxVar: string, the name of the GET variable indicating the ID of the element triggering the AJAX request
	 * - pagerClass: string, the CSS class for the pager container
	 * - sorterClass: string, the CSS class for the sorter container
	 * - updateSelector: string, the selector for choosing which elements can trigger ajax requests
	 * - beforeAjaxUpdate: function, the function to be called before ajax request is sent
	 * - afterAjaxUpdate: function, the function to be called after ajax response is received
	 */
	$.fn.yiiListView = function(options) {
		return this.each(function(){
			var settings = $.extend({}, $.fn.yiiListView.defaults, options || {});
			var $this = $(this);
			var id = $this.attr('id');
			if(settings.updateSelector == undefined) {
				settings.updateSelector = '#'+id+' .'+settings.pagerClass.replace(/\s+/g,'.')+' a, #'+id+' .'+settings.sorterClass.replace(/\s+/g,'.')+' a';
			}
			$.fn.yiiListView.settings[id] = settings;
                        if(settings.scrollTrigger == true){
                            console.log('enabling onScroll trigger')
                            console.log(settings)
                            //$.fn.yiiListView.update(id, {url: settings.updateSelector})
                     
                        if($.fn.yiiListView.triggerBound == false){
                            console.log($(settings.scrollContainerId))
                            
                            if(settings.scrollContainerId == 'window'){
                            $(window).bind('scroll',function(){$.fn.yiiListView.checkScroll(id)})
                                console.log('bind for window');
                            }
                            $(settings.scrollContainerId).bind('scroll.yiilist',function(){$.fn.yiiListView.checkScroll(id)})
                            //$(window).bind('scroll',function(){$.fn.yiiListView.checkScroll(id)})
                            $.fn.yiiListView.triggerBound =true
                            
                        }
                     //       console.log($(settings.updateSelector)[0].href)
                        }
			if(settings.ajaxUpdate.length > 0) {
				$(settings.updateSelector).die('click').live('click.yiilist',function(){
					$.fn.yiiListView.update(id, {url: $(this).attr('href')});
					return false;
				});
			}
		});
	};
        $.fn.yiiListView.runCount = 0;
        
        $.fn.yiiListView.triggerBound = false;
        
        $.fn.yiiListView.lock = false;
        
        $.fn.yiiListView.checkScroll = function(id){
            //console.log('checking scroll');
            var settings = $.fn.yiiListView.settings[id]

            
            var target;
            var targetScrollHeight;
                if(settings.scrollContainerId == 'window'){
                    target = $(window)
                    targetScrollHeight = $('body')[0].scrollHeight
                }
                else{
                    target = $(settings.scrollContainerId)
                    targetScrollHeight = $(target)[0].scrollHeight; 
                }
              //  console.log(target.scrollTop()+target.height()+parseInt(settings.scrollOffset)+' : '+ targetScrollHeight )
            if((target.scrollTop()+target.height()+parseInt(settings.scrollOffset)) >= targetScrollHeight && $.fn.yiiListView.lock == false){
                console.log('update triggered by srcoll')
                $.fn.yiiListView.lock = true;
        	$.fn.yiiListView.update(id, {url: $(settings.updateSelector)[0].href});
                console.log('lock set');
            }
        }

	$.fn.yiiListView.defaults = {
		ajaxUpdate: [],
		ajaxVar: 'ajax',
		pagerClass: 'pager',
		loadingClass: 'loading',
		sorterClass: 'sorter'
		// updateSelector: '#id .pager a, '#id .sort a',
		// beforeAjaxUpdate: function(id) {},
		// afterAjaxUpdate: function(id, data) {},
		// url: 'ajax request URL'
	};

	$.fn.yiiListView.settings = {};

	/**
	 * Returns the key value for the specified row
	 * @param id string the ID of the list view container
	 * @param index integer the zero-based index of the data item
	 * @return string the key value
	 */
	$.fn.yiiListView.getKey = function(id, index) {
		return $('#'+id+' > div.keys > span:eq('+index+')').text();
	};

	/**
	 * Returns the URL that generates the list view content.
	 * @param id string the ID of the list view container
	 * @return string the URL that generates the list view content.
	 */
	$.fn.yiiListView.getUrl = function(id) {
		var settings = $.fn.yiiListView.settings[id];
		return settings.url || $('#'+id+' > div.keys').attr('title');
	};

	/**
	 * Performs an AJAX-based update of the list view contents.
	 * @param id string the ID of the list view container
	 * @param options map the AJAX request options (see jQuery.ajax API manual). By default,
	 * the URL to be requested is the one that generates the current content of the list view.
	 */
	$.fn.yiiListView.update = function(id, options) {
		var settings = $.fn.yiiListView.settings[id];
		$('#'+id).addClass(settings.loadingClass);
		options = $.extend({
			type: 'GET',
			url: $.fn.yiiListView.getUrl(id),
			success: function(data,status) {
                                $.fn.yiiListView.runCount++
                                console.log('posted to '+$.fn.yiiListView.getUrl(id))
				$.each(settings.ajaxUpdate, function(i,v) {
                                    console.log(settings)
                                    var id = '#'+v;
                                    console.log(settings.updateSelector)					
                                    var d = data;
                                    if(settings.scrollTrigger == true){
                                         d = $(data).html();
                                    }
                                    // sprawdzic czy .pager a ma klase hidden, jesli tak, to zabic triggery
                                    if(settings.scrollTrigger == true && settings.scrollContainerId == 'window'){
                                        
                                         d = $(data).wrap('<div></div>').parent().html();
                                         var p = ($($(data)[1]).wrap('<div></div>').parent().html())
                                         
                                         if($($(p)).find('a').hasClass('hidden')){
                                             console.log('unbinding triggers')
                                             $(window).unbind('scroll');
                                             $(settings.updateSelector).die('click')
                                             
                                         }
                                         else
                                            d+=p
                                         //$(d).append($(data).children('.pager').wrap('<div></div>').parent().html())
                                         console.log(d)
                                         
                                    }
                                    $(settings.updateSelector).parent().replaceWith(d);
                                    if(settings.scrollTrigger == true && settings.scrollContainerId == 'window'){
                                        //$(settings.updateSelector).parent().append($($(data)[1]).wrap('<div></div>').parent().html());                                        
                                    }
                                    $.fn.yiiListView.lock = false;
                                    if($.fn.yiiListView.runCount >= settings.crossOver){
                                        if($.fn.yiiListView.scrollTrigger == true) $.fn.yiiListView.scrollTrigger = false
                                        else $.fn.yiiListView.scrollTrigger = true
                                        $.fn.yiiListView.runCount = -999
                                        console.log('crossover reached')
                                    }
                                    console.log('lock unset')
				});
				if(settings.afterAjaxUpdate != undefined)
					settings.afterAjaxUpdate(id, data);
				$('#'+id).removeClass(settings.loadingClass);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$('#'+id).removeClass(settings.loadingClass);
				alert(XMLHttpRequest.responseText);
                                $.fn.yiiListView.lock = false;
                                console.log('lock unset')
			}
		}, options || {});

		if(options.data!=undefined && options.type=='GET') {
			options.url = $.param.querystring(options.url, options.data);
			options.data = {};
		}
		options.url = $.param.querystring(options.url, settings.ajaxVar+'='+id);

		if(settings.beforeAjaxUpdate != undefined)
			settings.beforeAjaxUpdate(id);
		$.ajax(options);
	};

})(jQuery);